﻿using JESAI.ClamAV.NetScannerCore.Command;
using JESAI.ClamAV.NetScannerCore.Exceptions;
using JESAI.ClamAV.NetScannerCore.Extensions;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace JESAI.ClamAV.NetScannerCore.TcpClients.Builder
{
    public class TransientScannerTcpClientBuilder: IScannerTcpClientBuilder,IDisposable
    {
        public string Host { get; private set; }

        public int Port { get; private set; }
        public IScannerTCPClient SocketClient { get; private set; }

        public TransientScannerTcpClientBuilder()
        {
            this.SocketClient = new ScannerTCPClient();
        }                 

        public IScannerTCPClient Build()
        {
            Connect();
            return SocketClient;
        }
        public async Task<IScannerTCPClient> BuildAsync()
        {
             await ConnectAsync();
            return SocketClient;
        }
        private async Task ConnectAsync()
        {
            this.Host=this.Host ?? AppConst.Host;
            this.Port = this.Port<0? this.Port:  AppConst.Port;
            try
            {
                Close();
                await this.SocketClient.ConnectAsync(this.Host, this.Port);
            }catch(Exception ex)
            {
                throw new TCPServerException(this.Host, this.Port,ex);
            }
            
        }
        private void Connect()
        {
            try
            {
                Close();
                this.SocketClient.Connect(this.Host, this.Port);
            }
            catch(Exception ex)
            {
                throw new TCPServerException(this.Host, this.Port,ex);
            }          
        }

        public void Dispose()
        {
            Close();
        }

        public void Close()
        {           
            if (this.SocketClient != null&&this.SocketClient.Connected)
            {
                this.SocketClient.Close();
            }
        }
    }
}
